import React, { useEffect, useState } from 'react'
import { NavBar, Dialog, Toast } from 'antd-mobile'
import { Button } from '@nutui/nutui-react'
import { useNavigate } from 'react-router-dom'
import "../css/Harvest.scss"
import axios from 'axios'

// 收获地址
export default function Harvest() {
  let navigate = useNavigate()
  // 获取用户id
  let [userId] = useState(localStorage.getItem("userId"))
  const back = () => navigate(-1)
  // 地址列表
  let [harvest, setharvest] = useState([])
  // 获取地址
  let getassres = async () => {
    let data = await axios.get(`http://127.0.0.1:3000/users/address?userId=${userId}`)
    setharvest(data.data.data)
  }
  // 改变默认地址
  let setchecked = async (ids) => {
    let date = await axios.put(`http://127.0.0.1:3000/users/address?ids=${ids}&userId=${userId}`)
    if (date.data.code == 200) {
      getassres()
    }
  }
  // 删除地址
  let deladdress = async (ids) => {
    Dialog.confirm({
      content: '是否删除该地址',
      onConfirm: async () => {
        let date = await axios.delete(`http://127.0.0.1:3000/users/address?ids=${ids}&userId=${userId}`)
        if (date.data.code == 200) {
          getassres()
          Toast.show({
            icon: 'success',
            content: '删除成功',
            position: 'center',
          })
        }
      },
    })
  }
  useEffect(() => {
    getassres()
  }, [])
  return (
    <div className='harvest'>
      <NavBar onBack={back}>我的收货地址</NavBar>
      {harvest.map(item => (
        <div key={item._id} className='List'>
          <p className='List_p'>
            <span>{item.name}</span>
            <span>{item.phone}</span>
          </p>
          <p>
            收货地址：{item.address}
          </p>
          <p className='List_p'>
            <span>
              <input type="checkbox" checked={item.isdefault} onChange={() => { setchecked(item._id) }} />默认地址
            </span>
            <span>
              <button className='List_btn' onClick={()=>{navigate(`/addharvest?cateId=${item._id}`)}}>编辑</button>
              <button className='List_btn' onClick={() => { deladdress(item._id) }

              }>删除</button>
            </span>
          </p>
        </div>
      ))}
      <div className="btn">
        <Button block type="primary" color="#97b97d" onClick={() => { navigate('/addharvest') }}>
          添加新地址
        </Button>
      </div>

    </div>
  )
}
